from rest_framework import serializers
from user.models import User
import re
import logging
from rest_framework_jwt.utils import jwt_encode_handler, jwt_payload_handler

from django_redis import get_redis_connection
from django.contrib.auth import authenticate

logger = logging.getLogger('tenth_power')


class RegisterSerializer(serializers.ModelSerializer):
    sms_code = serializers.IntegerField(write_only=True)
    username = serializers.CharField()
    password = serializers.CharField(write_only=True)
    mobile = serializers.CharField()

    class Meta:
        model = User
        fields = ['username', 'password', 'sms_code', 'mobile']

    def create(self, validated_data):
        username = validated_data.get('username')
        password = validated_data.get('password')
        mobile = validated_data.get('mobile')

        sms_code = validated_data.get('sms_code')
        # 4.password检验
        if not re.match(r'^[a-zA-Z0-9]{6,20}$', password):
            raise serializers.ValidationError('password格式有误')
        use = User.objects.filter(username=username).count()
        if use:
            raise serializers.ValidationError('用户名重复注册')

        lists = User.objects.filter(mobile=mobile).count()
        if lists:
            raise serializers.ValidationError('手机号重复注册')
        # mobile检验
        print(mobile)
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            raise serializers.ValidationError('mobile格式有误')
        # 链接redis
        redis_conn = get_redis_connection('verify_code')

        # 取得sms_code
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        # 判断sms_code是否存在
        if not sms_code_server:
            raise serializers.ValidationError('短信验证码过期')
        if sms_code != int(sms_code_server):
            raise serializers.ValidationError('验证码有误')
        user = User.objects.create_user(
            username=username,
            password=password,
            mobile=mobile,
        )

        # 签发token
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return {
            'id': user.id,
            'username': user.username,
            'mobile': user.mobile,
            'token': token,
            'avatar':user.avatar
        }